package javaBasic;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class Java8arPallelStream {

//    public static void main(String[] args) {
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
////        List<Calendar> list =  Collections.synchronizedList(new ArrayList<>());
//        //上面并不能解决java并行流的问题 核心问题在于  sdf
////        format()方法中操作了一个成员变量calendar,且该方法上未加同步锁,说明该方法在多线程并发访问时,存在线程安全问题.
////        这就是上面测试代码中出现重复数据的根本原因.
////进一步查询得知,Java8以前的老版本中的日期和时间类全部都是线程不安全的,而在Java8新推出的日期类LocalDate和LocalDateTime非常友好的解决了上述问题.
//
//        List<Calendar> list =  Collections.synchronizedList(new ArrayList<>());
//
//        for (int i = 0; i < 20; i++) {
//            Calendar startDay = new GregorianCalendar();
//            Calendar checkDay = new GregorianCalendar();
//            checkDay.setTime(startDay.getTime());//不污染入参
//            checkDay.add(checkDay.DATE,i);
//            list.add(checkDay);
//            checkDay = null;
//            startDay = null;
//        }
//
//        list.stream().forEach(day ->  System.out.println(sdf.format(day.getTime())));
//        System.out.println("-----------------------");
////        有副作用的lambda表达式
//        list.parallelStream().forEach(day ->  System.out.println(sdf.format(day.getTime())));
//        System.out.println("-----------------------");
//    }

    public static void main(String[] args) {
        DateTimeFormatter fmt =  DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate date = LocalDate.now();
        List<LocalDate> list = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            LocalDate date1 = date.plusDays(i);
            list.add(date1);
        }
        list.stream().forEach(day ->  System.out.println(day.format(fmt)));
        System.out.println("-----------------------");
        list.parallelStream().forEach(day ->  System.out.println(day.format(fmt)));
    }


    public static void main2(String[] args) {
        DateTimeFormatter fmt =  DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDateTime date = LocalDateTime.now();
        List<LocalDateTime> list = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            LocalDateTime date1 = date.plusDays(i);
            list.add(date1);
        }
        list.stream().forEach(day ->  System.out.println(day.format(fmt)));
        System.out.println("-----------------------");
        list.parallelStream().forEach(day ->  System.out.println(day.format(fmt)));
    }


}
